//
//  ZCBaseRequestManager.m
//  UniversalApp
//
//  Created by 凯朱 on 2019/6/11.
//  Copyright © 2019 徐阳. All rights reserved.
//

#import "ZCBaseRequestManager.h"
#import "YQNetworking.h"
#import "Reachability.h"
#import "SLGuideVC.h"
@interface ZCBaseRequestManager()

@end


@implementation ZCBaseRequestManager
/*
 发起网络请求
 
 @param url url
 @param method 请求方式
 @param params 参数
 @param finished 完成回调
 */
+(void)requestWithUrl:(NSString *)url method:(ZCRequestMethod)method params:(NSDictionary *)params finished:(ZCRequiredFinished)finished{
    [self requestWithUrl:url method:method timeout:20 params:params finished:finished];
}

+(void)requestWithUrl:(NSString *)url method:(ZCRequestMethod)method timeout:(NSInteger)timeout params:(NSDictionary *)params finished:(ZCRequiredFinished)finished{
    if (kToken.length > 0) {
        [YQNetworking configHttpHeader:@{@"Authorization":kToken}];
    }
    NSString *startTime = [ZCTool isOpenDebugModel] ? [NSString dateStrFromDate:[NSDate date] formatStr:@"MM-dd HH:mm:ss.SSS"] : @"";
    if (timeout == 0) timeout = 20;
    [YQNetworking setupTimeout:timeout];
    if (method == GET) {
        [YQNetworking getWithUrl:url refreshRequest:NO cache:NO jsonRequest:YES params:params progressBlock:nil successBlock:^(id response) {
            [self handleResultWithResponse:response error:nil finished:finished];
            [self logWith:params startTime:startTime URLString:url result:response error:nil];
        } failBlock:^(NSError *error) {
            [self handleResultWithResponse:nil error:error finished:finished];
            [self logWith:params startTime:startTime URLString:url result:nil error:error];
        }];
    }else{
        [YQNetworking postWithUrl:url refreshRequest:NO cache:NO jsonRequest:YES params:params progressBlock:nil successBlock:^(id response) {
            [self handleResultWithResponse:response error:nil finished:finished];
            [self logWith:params startTime:startTime URLString:url result:response error:nil];
        } failBlock:^(NSError *error) {
            [self handleResultWithResponse:nil error:error finished:finished];
            [self logWith:params startTime:startTime URLString:url result:nil error:error];
        }];
    }
}


/*
 发起网络请求json请求
 
 @param url url
 @param method 请求方式
 @param params 参数
 @param finished 完成回调
 */
+(void)requestJsonWithUrl:(NSString *)url method:(ZCRequestMethod)method timeout:(NSInteger)timeout params:(NSDictionary *)params finished:(ZCRequiredFinished)finished{
    if (kToken.length > 0) {
        [YQNetworking configHttpHeader:@{@"Authorization":kToken}];
    }
    if (timeout == 0) timeout = 20;
    [YQNetworking setupTimeout:timeout];
    NSString *startTime = [ZCTool isOpenDebugModel] ? [NSString dateStrFromDate:[NSDate date] formatStr:@"MM-dd HH:mm:ss.SSS"] : @"";
    if (method == GET) {
        [YQNetworking getWithUrl:url refreshRequest:NO cache:NO jsonRequest:YES params:params progressBlock:nil successBlock:^(id response) {
            [self handleResultWithResponse:response error:nil finished:finished];
            [self logWith:params startTime:startTime URLString:url result:response error:nil];
        } failBlock:^(NSError *error) {
            [self handleResultWithResponse:nil error:error finished:finished];
            [self logWith:params startTime:startTime URLString:url result:nil error:error];
        }];
    }else{
        [YQNetworking postWithUrl:url refreshRequest:NO cache:NO jsonRequest:YES params:params progressBlock:nil successBlock:^(id response) {
            [self handleResultWithResponse:response error:nil finished:finished];
            [self logWith:params startTime:startTime URLString:url result:response error:nil];
        } failBlock:^(NSError *error) {
            [self handleResultWithResponse:nil error:error finished:finished];
            [self logWith:params startTime:startTime URLString:url result:nil error:error];
        }];
    }
}

+(void)requestJsonWithUrl:(NSString *)url method:(ZCRequestMethod)method  params:(NSDictionary *)params finished:(ZCRequiredFinished)finished{
    [self requestJsonWithUrl:url method:method timeout:20 params:params finished:finished];
}

+(void)deleteWithUrl:(NSString *)url params:(NSDictionary *)params finished:(ZCRequiredFinished)finished{
    NSString *startTime = [ZCTool isOpenDebugModel] ? [NSString dateStrFromDate:[NSDate date] formatStr:@"MM-dd HH:mm:ss.SSS"] : @"";
    [YQNetworking deleteWithUrl:url refreshRequest:NO cache:NO jsonRequest:NO params:params progressBlock:nil successBlock:^(id response) {
        [self logWith:params startTime:startTime URLString:url result:response error:nil];
        [self handleResultWithResponse:response error:nil finished:finished];
    } failBlock:^(NSError *error) {
        [self logWith:params startTime:startTime URLString:url result:nil error:error];
        [self handleResultWithResponse:nil error:error finished:finished];
    }];
}

+(void)logWith:(id)parameters startTime:(NSString*)startTime URLString:(NSString *)URLString result:(id)result error:(NSError *)error{
    if ([ZCTool isOpenDebugModel]) {
        NSString *logLevel = kSTRING([[NSUserDefaults standardUserDefaults] objectForKey:@"openDebugLogLevel"]);
        if ([logLevel isEqualToString:@"1"]) {
            result = @"";
        }
        NSString *endTime = [NSString dateStrFromDate:[NSDate date] formatStr:@"MM-dd HH:mm:ss.SSS"];
        NSString *logMsg = [NSString stringWithFormat:@"【请求url】%@\n【开始时间】%@\n【结束时间】%@\n【请求参数】%@\n【error】%@\n【返回体】%@\n",URLString,startTime,endTime,parameters,kSTRING(error.description),result];
        [UserManager updateLogViewWithMessage:logMsg needUnicode:YES];
    }
}

#pragma mark - ————— 图片上传 <表单专用> —————

/**
 处理网络请求结果
 
 @param response 响应体
 @param error 错误
 */
+(void)handleResultWithResponse:(id)response error:(NSError *)error
                       finished:(ZCRequiredFinished)finished{
    
    //请求错误
    if (error) {
        NSString *desc = kSTRING(error.description);
        NSLog(@"desc = %@",error.description);
        BOOL isSessionOut =  NO;
        isSessionOut =  [desc containsString:@"(401)"] && [desc containsString:@"unauthorized"];
        if (isSessionOut) {
            //清理token缓存
            [ZCTool hideLoadingOnKeyWindow];
            [[UserManager sharedUserManager] clearUserInfo];
            [[SLBluetoothManager sharedManager] disConnectPeripheral];
            if (![[ZCTool getCurrentUIVC] isKindOfClass:[SLGuideVC class]]) {
                KPostNotification(KNotificationLoginStateChange, @NO);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    kShowToast(@"Login status expired");
                });
            }
            return;
        }
        
        NSString *message = [self getNetworkErrorMessageWith:error.code];
        if (finished) finished(NO,@"",@"",message);
        return;
    }
    
    NSString *code = kSTRING(response[@"code"]);
    NSString *message = kSTRING(response[@"message"]);
    if (message.length == 0) {
        message = kSTRING(response[@"msg"]).length > 0 ? kSTRING(response[@"msg"]):kLocalString(@"No Internet Connection");
    }
    
    //校验数据格式
    if (response == nil || ![response isKindOfClass:[NSDictionary class]]) {
        if (finished) finished(NO,response,@"",kLocalString(@"No Internet Connection"));
        return;
    }
    
    //校验code码是否正常
    if (![code isEqualToString:@"200"]) {
        if (finished) finished(NO,response,code,message);
        return;
    }
    
    NSString *message2 = kSTRING(response[@"message"]);
    if ([code isEqualToString:@"0"] && message2.length == 0) {
        message = kLocalString(@"Handle success");
    }
   
    //请求成功回调
    if (finished) finished(YES,response,code,message);
}


/*
 解析错误码
 
 @param code 返回提示
 */
+(NSString *)getNetworkErrorMessageWith:(NSInteger)code{
    NSString *errorMesg = kLocalString(@"No Internet Connection");
    if(![self checkNetWork])//没有网络
    {
        return kLocalString(@"Client has no valid network connection");
    }
    
    switch (code) {
        case -1001://NSURLErrorTimedOut
            errorMesg = kLocalString(@"Network request timeout");
            break;
        case -1005://NSURLErrorNetworkConnectionLost
            errorMesg = kLocalString(@"Network connection exception");
            break;
        case -1011://NSURLErrorBadServerResponse
            errorMesg = kLocalString(@"Service is busy, please try again later");
            break;
        case -999://请求被取消了不提示
            errorMesg = @"";
            break;
    }
    return errorMesg;
}

#pragma mark -
#pragma mark - ================<网络、其他校验>===============
/**
 网络检查
 
 @return YES-有网络 NO-无网络
 */
+(BOOL)checkNetWork{
    
    BOOL isHaveNet = YES;
    Reachability *r = [Reachability reachabilityWithHostName:URL_main];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:{
            isHaveNet = NO;
            break;
        }
        case ReachableViaWiFi: case ReachableViaWWAN:{
            isHaveNet = YES;
            break;
        }
        default:{
            break;
        }
    }
    return isHaveNet;
}

@end
